package com.kylin.log.service;

import com.kylin.log.dto.LogDto;
import com.kylin.log.entity.PageImpl;
import com.kylin.common.log.entity.AopLogEntity;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class LogService {

    @Autowired
    MongoTemplate mongoTemplate;

    public void saveLog(AopLogEntity aopLogEntity){
        mongoTemplate.save(aopLogEntity,"log");
    }

    public PageImpl findLog(LogDto logDto) {

        if (logDto.getPageNo()<0){
            logDto.setPageNo(1);
        }
        if (logDto.getPageSize()<0){
            logDto.setPageSize(1);
        }
        Query query = new Query();
        if (StringUtils.isNotBlank(logDto.getIp())){
            query.addCriteria(Criteria.where("ip").is(logDto.getIp()));
        }
        if (StringUtils.isNotBlank(logDto.getClassName())){
            query.addCriteria(Criteria.where("className").is(logDto.getClassName()));

        }
        long count = mongoTemplate.count(query, AopLogEntity.class, "log");

        query.skip((logDto.getPageNo()-1)*logDto.getPageSize());
        query.limit(logDto.getPageSize());
        List<AopLogEntity> list = mongoTemplate.find(query, AopLogEntity.class, "log");

        return new PageImpl(count,list);
    }
}
